package com.giser.testapp;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;

import com.giser.testapp.lib.App.EnvApplication;
import com.giser.testapp.lib.App.GlobClass;
import com.giser.testapp.lib.Tool.EnvLog;
import com.giser.testapp.lib.Tool.NotificationsUtils;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Lss on 2017/12/12.
 */

public class CheckPermissionsActivity extends AppCompatActivity {
    /**
     * 需要进行检测的权限数组
     */
    String[] needPermissions = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.CAMERA
    };

    private static final int PERMISSON_REQUESTCODE = 0;

    /**
     * 判断是否需要检测，防止不停的弹框
     */
    protected boolean isNeedCheck = true;
    protected boolean isToast=false;

    @Override
    protected void onResume() {
        super.onResume();
        EnvLog.i("onResume");
        checkPermiss();
    }

    protected  void checkPermiss(){
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            if (isNeedCheck) {
                EnvLog.i("checkPermissions");
                checkPermissions(needPermissions);
            }else{
                EnvLog.i("isNeedCheck=false");
                if(!isToast){
                    EnvLog.i("!isToast");
                    checkStartLocationServer();
                }
            }
        }else{checkStartLocationServer();}
    }
    private void checkStartLocationServer(){
        EnvLog.i("checkStartLoc");
        if(EnvApplication.getApplication().locationModuleTag==0){
            EnvLog.i("checkStartLoc==0");
            EnvApplication.getApplication().getLocationServer(this).start();
        }
    }
    /**
     *
     * @param permissions
     * @since 2.5.0
     *
     */
    private void checkPermissions(String... permissions) {
        try {
            if (Build.VERSION.SDK_INT >= 23
                    && getApplicationInfo().targetSdkVersion >= 23) {
                List<String> needRequestPermissonList = findDeniedPermissions(permissions);
                if (null != needRequestPermissonList
                        && needRequestPermissonList.size() > 0) {
                    String[] array = needRequestPermissonList.toArray(new String[needRequestPermissonList.size()]);
                    Method method = getClass().getMethod("requestPermissions", new Class[]{String[].class,
                            int.class});

                    method.invoke(this, array, PERMISSON_REQUESTCODE);
                }
            }
        } catch (Throwable e) {
        }
    }

    /**
     * 获取权限集中需要申请权限的列表
     *
     * @param permissions
     * @return
     * @since 2.5.0
     *
     */
    private List<String> findDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissonList = new ArrayList<String>();
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23){
            try {
                for (String perm : permissions) {
                    Method checkSelfMethod = getClass().getMethod("checkSelfPermission", String.class);
                    Method shouldShowRequestPermissionRationaleMethod = getClass().getMethod("shouldShowRequestPermissionRationale",
                            String.class);
                    if ((Integer)checkSelfMethod.invoke(this, perm) != PackageManager.PERMISSION_GRANTED
                            || (Boolean)shouldShowRequestPermissionRationaleMethod.invoke(this, perm)) {
                        needRequestPermissonList.add(perm);
                    }
                }
            } catch (Throwable e) {

            }
        }
        return needRequestPermissonList;
    }

    /**
     * 检测是否所有的权限都已经授权
     * @param grantResults
     * @return
     * @since 2.5.0
     *
     */
    private boolean verifyPermissions(int grantResults) {
        if (grantResults != PackageManager.PERMISSION_GRANTED) {
            return false;
        }
        return true;
    }

    @TargetApi(23)
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] paramArrayOfInt) {
        if (requestCode == PERMISSON_REQUESTCODE) {
            StringBuilder stringBuilder=new StringBuilder();
            for(int i=0;i<permissions.length;i++){
                if (!verifyPermissions(paramArrayOfInt[i])) {
                    stringBuilder.append( getNotifyContent(permissions[i]));
                }
            }
            if(!NotificationsUtils.isNotificationEnabled(this)){
                stringBuilder.append("\n开启通知，实时接收工单信息！ \n");
            }
            if (stringBuilder.length()>0) {
                isToast=true;
                EnvLog.i("str="+stringBuilder.toString());
                showMissingPermissionDialog(stringBuilder.toString());
            }else{isToast=false;}
            isNeedCheck = false;
        }
    }

    private String getNotifyContent(String item){
        String result="";
        switch (item){
            case Manifest.permission.ACCESS_COARSE_LOCATION:
                result="\n应用缺少访问粗略位置的权限!\n";
                break;
            case Manifest.permission.ACCESS_FINE_LOCATION:
                result="\n应用缺少访问精确位置的权限!\n";
                break;
            case Manifest.permission.WRITE_EXTERNAL_STORAGE:
                result="\n应用缺少写入外部存储的权限!\n";
                break;
            case Manifest.permission.READ_EXTERNAL_STORAGE:
                result="\n应用缺少读取外部存储的权限!\n";
                break;
            case Manifest.permission.READ_PHONE_STATE:
                result="\n应用缺少读取电话状态的权限!\n";
                break;
            case Manifest.permission.CAMERA:
                result="\n应用缺少访问照相设备的权限!\n";
                break;
            default:
                break;
        }
        return result;
    }
    /**
     * 显示提示信息
     *
     * @since 2.5.0
     *
     */
    private void showMissingPermissionDialog(String content) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.notifyTitle);
        builder.setMessage(content);

        // 拒绝, 退出应用
        builder.setNegativeButton(R.string.cancel,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        EnvLog.i("finsh..ljdf");
                        finish();
                    }
                });

        builder.setPositiveButton(R.string.setting,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startAppSettings();
                    }
                });

        builder.setCancelable(false);

        builder.show();
    }

    /**
     *  启动应用的设置
     *
     * @since 2.5.0
     *
     */
    private void startAppSettings() {
        Intent intent = new Intent(
                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivityForResult(intent, GlobClass.CheckPermission_CODE);
    }
}
